package com.csair.common.utils;

import android.content.Context;
import android.content.res.Resources;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.csair.common.AppUtilsConfig;
import com.csair.common.CommonApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.TimeZone;
import java.util.UUID;

public final class DeviceUtils {




    private static final String PATH = Environment.getExternalStorageDirectory().toString() + AppUtilsConfig.APP_PACKAGE_NAME;
    private static final String TAG = "DeviceUtils";
    //"-"在读取时也被算入，所以长度是32+4
    private static int DEVICEIDLENGTH = 36;

    /**
     * 获取设备ID并加密
     */
    public static String getDeviceId() {
        String uniqueId;
        uniqueId = loadDeviceId();
        if(!TextUtils.isEmpty(uniqueId)){
            //从SD卡或SP中获取到了id则直接返回，否则去生成一个
            return uniqueId;
        }
        saveNewDeviceId();
        return loadDeviceId();
    }
    /**
     * 首次启动，检查SD卡和SP的情况
     * 只要可以读写SD卡，此时优先SD卡中的值，并存入SP
     */
    public static void checkFirstDeviceID(){
        //首次开启app检查SD卡中有没有数据，有则将SD卡中的数据写入SP，否则生成新的
        String deviceIdSP = getDevicesIdFromSp();
        String deviceIdSD = readDeviceID();
        if(deviceIdSD.length() == DEVICEIDLENGTH){
            if(!deviceIdSD.equals(deviceIdSP)){
                deviceIdSP = deviceIdSD;
                setDeviceIdToSp(deviceIdSP);
            }
        } else {
            if(!(deviceIdSP.length() == DEVICEIDLENGTH)){
                saveNewDeviceId();
            }
        }
    }
    /**
     * 除了首次启动，每次启动时检查SD卡和SP的情况
     * 如果SD卡为空或者两者不同，尝试将SP中的数据写入SD卡,以SP为准
     */
    public static void checkDeviceID(){
        String deviceIdSP = getDevicesIdFromSp();
        String deviceIdSD = readDeviceID();
        LogUtils.i(TAG,"deviceIdSP:"+deviceIdSP+",deviceIdSD"+deviceIdSD);
        if(deviceIdSP.length() == DEVICEIDLENGTH){
            //可能被手动修改或者没有对应文件，尝试将SP中的数据写入SD卡,以SP为准
            if((deviceIdSD.length() != DEVICEIDLENGTH) || (!deviceIdSP.equals(deviceIdSD))){
                writeDeviceID(deviceIdSP);
            }
        }
    }





    /*************************************************/
    private static void setDeviceIdToSp(String deviceId){
        SharedPreferencesUtil.getInstance(AppUtilsConfig.PREFERENCE_APPCONFIG_FILENAME).getSharePreferencesSingleton().edit().putString(AppUtilsConfig.DEVICE_ID_DEFAULT, deviceId).commit();
    }
    private static String getDevicesIdFromSp(){
        return SharedPreferencesUtil.getInstance(AppUtilsConfig.PREFERENCE_APPCONFIG_FILENAME).getString(AppUtilsConfig.DEVICE_ID_DEFAULT,"");
    }



    private static void saveNewDeviceId(){
        //进入前提前请求所有权限,生成时不再判断
        String androidId = Secure.getString(CommonApplication.getApplication().getContentResolver(), Secure.ANDROID_ID);
        if (androidId == null) androidId = "";

        TelephonyManager tm = (TelephonyManager) CommonApplication.getApplication().getSystemService(Context.TELEPHONY_SERVICE);
        String tmDevice = "", tmSerial = "";
        try {
            tmDevice = "" + tm.getDeviceId();
            tmSerial = "" + tm.getSimSerialNumber();
        } catch (SecurityException e) {
            LogUtils.printStackTrace(e);
        }

        LogUtils.i(TAG,"androidId:"+androidId+",tmDevice:"+tmDevice+",tmSerial"+tmSerial);

        UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();

        if (TextUtils.isEmpty(uniqueId)) {
            String temp = CommonApplication.getApplication().getSharedPreferences("Device",
                    Context.MODE_PRIVATE).getString("IMEI", "*");
            if (!"".equals(temp) && !"*".equals(temp)) {
                uniqueId = temp;
            } else {
                Random random = new Random((long) 10e16);
                random.nextLong();
                uniqueId = String.valueOf(random.nextLong());
                CommonApplication.getApplication().getSharedPreferences("Device", Context.MODE_PRIVATE)
                        .edit().putString("IMEI", uniqueId).apply();
            }
        }
        //将deviceID写入SP和SD卡
        setDeviceIdToSp(uniqueId);

        String id = getDevicesIdFromSp();
        if(id.length() == DEVICEIDLENGTH){
            writeDeviceID(id);
        }
    }
    /**
     * 从SD卡或SP中获取到了id则直接返回
     * @return deviceID
     */
    private static String loadDeviceId(){
        String deviceID = "";
        //最先从sp获取deviceID
        deviceID = getDevicesIdFromSp();
        if(!TextUtils.isEmpty(deviceID)){
            LogUtils.i(TAG,"SP-GET:"+deviceID);
            return deviceID;
        }
        //未获取到时，从sp获取deviceID
        deviceID = readDeviceID();
        LogUtils.i(TAG, "SD-GET:" + deviceID);
        return deviceID;
    }
    private static String readDeviceID(){
        String id = "";
        try{
            File file = new File(PATH+".dvc.txt");
            if(file.exists()){
                InputStream inputStream = new FileInputStream(file);
                InputStreamReader inputReader = new InputStreamReader(inputStream);
                BufferedReader buff = new BufferedReader(inputReader);
                String getLine = buff.readLine();
                if(getLine.length() == DEVICEIDLENGTH){
                    id = getLine;
                } else {
                    file.delete();//位数对不上，说明被改过，直接删除
                }
                inputStream.close();
            }
        }catch (Exception e){
            LogUtils.printStackTrace(e);
        }
        return id;
    }
    private static void writeDeviceID(String id){
        try{
            File filepath = new File(PATH);
            File file = new File(PATH+".dvc.txt");
            if(!filepath.exists()){
                filepath.mkdirs();
            }
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(id.getBytes());
            outputStream.flush();
            outputStream.close();
            LogUtils.i(TAG,"writeFinish");
        } catch(Exception e){
            LogUtils.printStackTrace(e);
        }
    }







    /*************************************************/


    /**
     * @return 获取手机型号
     */
    public static String getEquipmentModel() {
        return Build.MODEL;
    }
    /**
     * 获取手机系统版本
     */
    public static String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }
    /**
     * 获取设备当前MAC地址
     */
    public static String getMacAddress(Context context) {
        String mac = "";
        try {
            WifiManager wifiMng = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            return wifiMng.getConnectionInfo().getMacAddress();
        } catch (Exception e) {
            LogUtils.printStackTrace(e);
        }

        return mac;
    }
    /**
     * 获取设备IMEI码
     * @param context Application Context
     * @return IMEI码
     */
    public static String getDeviceId(Context context) {
        String id = "";
        try {
            TelephonyManager mTelephony = (TelephonyManager) context.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
            if (mTelephony.getDeviceId() != null) {
                id = mTelephony.getDeviceId();
            }
        } catch (Exception e) {
            LogUtils.printStackTrace(e);
        }
        return id;
    }
    /**
     * 获取当前时区
     * @return
     */
    public static String getCurrentTimeZone() {
        try {
            TimeZone tz = TimeZone.getDefault();
            String strTz = tz.getDisplayName(false, TimeZone.SHORT);

            if (!TextUtils.isEmpty(strTz)) {
                return strTz;
            }
        } catch (Exception e) {

        }
        return "";
    }
    public static String getCurrentTimeZoneFormat() {
        String timeZone = getCurrentTimeZone();
        if (!TextUtils.isEmpty(timeZone)) {
            timeZone = timeZone.trim();
            if (timeZone.contains(" ")) timeZone.replace(" ", "%2B");//url，+是特殊字符，需要转义
            if (timeZone.contains("\\+")) timeZone.replace("+", "%2B");//url，+是特殊字符，需要转义
        }
        return timeZone;
    }

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }


    public static int getWindowWidth(Context context){
        // 获取屏幕分辨率
        WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int mScreenWidth = dm.widthPixels;
        return mScreenWidth;
    }
    public static int getWindowHeight(Context context) {
        // 获取屏幕分辨率
        WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int mScreenHeigh = dm.heightPixels;
        return mScreenHeigh;


    }




}
